const http = require('http')
const data= require('./data')
let app = http.createServer((req,res)=>{
  res.setHeader('content-type','text/html;charset=utf-8')
  let {pathname,searchParams}=new URL(req.url,'http://localhost:8000')
  // console.log(searchParams);
  if (pathname ==='/'){
    let str =`<a href="/list">前往列表页</a>`
    res.end(str)
  }else if(pathname === '/list'){
    let str='<h1>新闻列表</h1><ul>'
    data.forEach((itme) => {
      str+=`<li><a href='/detial?id=${itme.id}'>${itme.newsTitle}</a></li>`
    });
    str+'</ul>'
    res.end(str)
  }else if(pathname ==='/detial'){
    let id=searchParams.get('id')
    // console.log(id);
    let obj=data.find((itme)=>{
      return itme.id===id
    })

    if(!obj){
      res.end(`<p>抱歉，您访问的页面不存在</p><a href="/list">返回新闻列表</a>`)
      return
    }

    let str=`
      <h3>${obj.newsTitle}</h3>
      <p>${obj.newsContent}</p>
      <a href="/list">返回新闻列表</a>
    `
    res.end(str)
  }else{
    let str =`<p>地址错误，404</p><a href="/">返回首页</a>`
    res.end(str)
  }
  

  
})

app.listen(8000,()=>{
  console.log('启动成功');
})